import {Injectable} from '@angular/core';
import {environment} from '../../environments/environment';
import {CronJob} from 'cron';
import {AppAuthService} from './app-auth.service';
import {EventsService} from './events/Events.service';
import {IEvent} from './events/EventM';
import {LoginStatusFailureEvent} from './events/LoginStatusFailureEventHandle';
import {DateTime} from 'luxon';

@Injectable({
  providedIn: 'root',
})
export class AppTokenTaskService {
  //定时更新token的job
  private refreshTokenJob: CronJob;
  public refreshTokenJobstack: boolean = false;

  //AppServerService刷新页面都会销毁重建
  constructor(private appAuthService: AppAuthService,
              private appEventsService: EventsService<IEvent>
  ) {
    console.log('AppTaskService --- constructor');
    console.log("环境配置文件", environment);

    this.refreshTokenJob = new CronJob(
      '0/5 * * * * *',
      this.refreshTokenTask.bind(this), // .bind(this) 固定函数体内的this指向
      null, // onComplete
      false,
      'America/Los_Angeles'
    )
  }

  //定时检测登录状态任务
  //定时更新token任务
  async refreshTokenTask() {
    console.log('AppTaskService --- refreshTokenTask >>>start', DateTime.now().toMillis());
    //1判断登录状态
    const isLoggedIn = await this.appAuthService.isLoggedIn();
    console.log("isLoggedIn>>>结果", isLoggedIn)
    if (isLoggedIn === false) {
      // 没登录/登录期
      console.log("refreshTokenTask没有登录,无需再刷新,  停止RefreshTokenTask");
      //发布登录状态NotLoginEvent事件
      this.appEventsService.broadcastEvent(new LoginStatusFailureEvent('isLoggedIn检查结果'));
      //this.stopRefreshTokenTask();
    } else {
      //登录状态正常时 判断接口token
      this.appAuthService.refreshToken(isLoggedIn);
    }
  }

  startRefreshTokenTask() {
    if (!this.refreshTokenJobstack) {
      console.log('AppTaskService --- startRefreshTokenTask');
      this.refreshTokenJob.start();
      this.refreshTokenJobstack = true;
    }
  }

  stopRefreshTokenTask() {
    if (this.refreshTokenJobstack) {
      console.log('AppTaskService --- stopRefreshTokenTask');
      this.refreshTokenJob.stop();
      this.refreshTokenJobstack = false;
    }
  }

}
